import { getUserInfoByToken } from '@/api/user/user';
import cookies from '@/utils/cookies.js';

const USER_BASE_INFO = {
  id: '',
  username: '',
  name: '',
  description: ''
};

let token = cookies.get('token') || '';

export default {
  namespaced: true,
  state: {
    sid: '',
    token: token,
    info: {
      ...USER_BASE_INFO
    }
  },
  getters: {
    g_sid(state) {
      return state.sid;
    },
    g_token(state) {
      return state.token;
    }
  },
  mutations: {
    s_sid(state, sid) {
      state.sid = sid;
    },
    s_token(state, token) {
      state.token = token;
      cookies.set('token', token);
    },
    s_user(state, info){
      state.info.id = info.id;
      state.info.username = info.username;
    }
  },
  actions: {
    load({ state, dispatch }) {
      let params = {
        token: state.token
      };
      return new Promise(async resolve => {
        // 开始请求登录接口
        getUserInfoByToken(params)
          .then(async res => {
            let { id, username, name, description, menus } = res;
            await dispatch(
              'base/user/set',
              {
                id,
                username,
                name,
                description
              },
              {
                root: true
              }
            );
            await dispatch(
              'base/menu/fnGenerateRoutes',
              {
                menus
              },
              {
                root: true
              }
            );
            resolve();
          })
          .catch(err => {
            console.log('err: ', err);
          });
      });
    },
    set({ state, dispatch }, info) {
      return new Promise(async resolve => {
     
        // store 赋值
        state.info = {
          ...USER_BASE_INFO,
          ...info
        };
        // 持久化
        await dispatch(
          'base/db/set',
          {
            dbName: 'sys',
            path: 'user.info',
            value: info,
            user: true
          },
          { root: true }
        );
        // end
        resolve();
      });
    }
  }
};
